package com.aqie.easy.hash;

import java.util.HashMap;
import java.util.Map;

/**
 * 953 验证外星语词典
 */
public class IsAlienSorted {
    Map<Character, Integer> map = new HashMap<>();
    public boolean isAlienSorted(String[] words, String order) {
        for (int i = 0; i< order.length(); i++){
            map.put(order.charAt(i), i);
        }
        for (int i = 0; i < words.length - 1; i++){
            if(!isOrder(words[i], words[i + 1])){
                return false;
            }
        }
        return true;
    }

    private boolean isOrder(String a, String b){
        int length = a.length() >= b.length() ? b.length() : a.length();
        String c = a.length() < b.length() ? b : a;

        // 检测 ab字符串是否按顺序
        for (int i = 0; i < length; i++)
            if (map.get(a.charAt(i)) < map.get(b.charAt(i))) return true;
            else if (map.get(a.charAt(i)) > map.get(b.charAt(i))) {
                return false;
            }else{
                // 两个字符相等才检测 单个字符是否排序
                if (map.get(a.charAt(i)) > map.get(a.charAt(i + 1))) return false;
            }

        return true;
    }

    public static void main(String[] args) {
        String[] arr = {"hello","leetcode"};
        String order = "hlabcdefgijkmnopqrstuvwxyz";

        String[] arr2 = {"word","world","row"};
        String order2 = "worldabcefghijkmnpqstuvxyz";

        String[] arr3 = {"apple","app"};
        String order3 = "abcdefghijklmnopqrstuvwxyz";

        String[] arr4 = {"apoel","apo"};
        String order4 = "abcdefghijklmnopqrstuvwxyz";

        System.out.println(new IsAlienSorted().isAlienSorted(arr, order));
        // 1.重叠部分未排序
        System.out.println(new IsAlienSorted().isAlienSorted(arr2, order2));
        // 2.长字母未排序
        System.out.println(new IsAlienSorted().isAlienSorted(arr3, order3));
        // 3.短字母未排序
        System.out.println(new IsAlienSorted().isAlienSorted(arr4, order4));
    }
}
